/*
	   _           _      _           _     _ 
	  (_)         | |    | |         (_)   | |
	   _ _   _ ___| |_ __| |_ __ ___  _  __| |
	  | | | | / __| __/ _` | '__/ _ \| |/ _` |
	  | | |_| \__ \ || (_| | | | (_) | | (_| |
	  | |\__,_|___/\__\__,_|_|  \___/|_|\__,_|
	 _/ |                                     
	|__/ 
	
	Copyright 2013 Caspar Isemer and and Eva Krueger, http://justdroid.org	
	
	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at
	
		http://www.apache.org/licenses/LICENSE-2.0
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License. 
*/

package org.justdroid.justdroid;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.method.KeyListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class JustDroidActivity extends Activity implements KeyListener{
	
	/** Declare variables used for the Screen Curtain feature **/
	protected View curtainView;
	protected boolean curtainSet = false;
	
	/** Function to attach onTouchListener and onFocusListener to the buttons **/
	void attachListener(Button button) {
		final String text = button.getText().toString();
		/*button.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View view, MotionEvent arg1) {
				giveFeedback(text);
				return false;
			}
		});*/
		button.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if(hasFocus) {
					giveFeedback(text);
				}
			}
		});
	}
	
	/** Function to announce the text of the view that received focus or on which the onTouch event was triggered**/
	void giveFeedback(String text) {
		//vibrate
		Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	    vibrator.vibrate(300);
	    //TTS feedback
	    if(!TTS.isSpeaking())
	    	TTS.speak(text);
	}
	
	/** Launch the respective Java class, depending on which button is pressed **/
	void setKeyDownClass(Context context, Intent intent) {
	    startActivity(intent);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		/** Screen Curtain functionality **/
		WindowManager windowManager = getWindowManager();
		LayoutInflater inflater = getLayoutInflater();
		LayoutParamsAndViewUtils layoutParamsAndView = ScreenCurtainFunctions.prepareForCurtainCheck(inflater);
    	
    	ScreenCurtainFunctions appState = ((ScreenCurtainFunctions) getApplicationContext());
    	if(appState.getState() && !curtainSet) {
    		curtainView = layoutParamsAndView.getView();
    		windowManager.addView(curtainView, layoutParamsAndView.getLayoutParams());
    		curtainSet = true;
    	} else if(!appState.getState() && curtainSet) {
    		windowManager.removeView(curtainView);
    		curtainSet = false;
    	} 	
	}
	
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/** Find justdroid-specific Back and Home buttons **/
		Button btnNavigationBack = (Button) findViewById(R.id.btnNavigationBack);
		Button btnNavigationHome = (Button) findViewById(R.id.btnNavigationHome);
		
		/** If Back navigation button is pressed, go back to previous activity **/
		btnNavigationBack.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	//TTS.speak(((TextView)v).getText().toString());
	        	finish();
	        }
	    });

		/** If Home navigation button is pressed, go back to previous activity **/
		btnNavigationHome.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	//TTS.speak(((TextView)v).getText().toString());
	        	finish();
	        	Intent intent = new Intent(getApplicationContext(), SwipingUtils.class);
	        	intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        	intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
	        	startActivity(intent);
	        }
	    });
		
		OnFocusChangeListener focusChangeListener = new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View view, boolean hasFocus) {
				if(hasFocus) {
					TTS.speak(((TextView)view).getText().toString());
				}
			}
		};
		
		btnNavigationBack.setOnFocusChangeListener(focusChangeListener);
		btnNavigationHome.setOnFocusChangeListener(focusChangeListener);
	}
	
	/** Launch the respective Java class, depending on which button is pressed **/
	void setButtonClickAppClass(int buttonInt, final Context ctx, final Class<?> cls) {
		Button button = (Button) findViewById(buttonInt);
		button.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	Intent intent = new Intent(ctx, cls);
	            startActivity(intent);
	        }
	    });
	}
	
	/** Launch the respective Java class, depending on which textview is pressed **/
	void setTextviewClickAppClass(int textviewInt, final Context ctx, final Class<?> cls) {
		TextView textview = (TextView) findViewById(textviewInt);
		textview.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	Intent intent = new Intent(ctx, cls);
	            startActivity(intent);
	        }
	    });
	}
	
	/** Launch the respective Android app, depending on which button is pressed **/
	void setButtonClickUri(int buttonInt, final String uriTarget) {
		Button button = (Button) findViewById(buttonInt);
		button.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	launchOrDownloadFromActivity(uriTarget);
	        }
	    });
	}
	
	/** Launch the respective Android intent, depending on which button is pressed **/
	void setButtonClickIntent(int buttonInt, final String intentTarget) {
		Button button = (Button) findViewById(buttonInt);
		button.setOnClickListener(new View.OnClickListener() {
	        public void onClick(View v) {
	        	Intent intent = new Intent(intentTarget);
	        	startActivity(intent);
	        }
	    });
	} 	
	
	/** Launch installed Android app or download from Google Play Store if missing **/
	void launchOrDownloadFromActivity(String uriTarget) {
		Intent intent = getPackageManager().getLaunchIntentForPackage(uriTarget);
    	if (intent != null)
    	{
    		// Start installed app
    	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	    startActivity(intent);
    	}
    	else
    	{
    		// If app is not installed, bring user to the Play Store
    	    intent = new Intent(Intent.ACTION_VIEW);
    	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	    intent.setData(Uri.parse("market://details?id="+uriTarget));
    	    
    	    // Error handling in case Play Store cannot be launched
    	    try {
    	    	startActivity(intent);
    	    } catch(ActivityNotFoundException e) {
	        	Context context = getApplicationContext();
	        	CharSequence text = "Unable to launch the Google Play Store!";
	        	Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    	    }
    	}
	}
	
	public void sendIntent(Intent intent) {
		startActivity(intent);
	}
	
	@Override
	public void clearMetaKeyState(View arg0, Editable arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int getInputType() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public boolean onKeyDown(View view, Editable arg1, int keyCode, KeyEvent keyEvent) {
		if(keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
			switch(keyCode) {
				case KeyEvent.KEYCODE_BACK:
					TTS.speak("Back");
		        	finish();
		        	break;
				case KeyEvent.KEYCODE_F1:
					TTS.speak("Home");
					finish();
					Intent intent = new Intent(getApplicationContext(), SwipingUtils.class);
		        	intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        	intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
		        	startActivity(intent);
		        	break;
			}
		}
		return false;
	}

	@Override
	public void onBackPressed() {
		finish();
	}
	
	@Override
	public boolean onKeyOther(View arg0, Editable arg1, KeyEvent arg2) {
		return false;
	}

	@Override
	public boolean onKeyUp(View view, Editable arg1, int keyCode, KeyEvent keyEvent) {
		switch(keyCode) {
		case KeyEvent.KEYCODE_TAB:
			if(keyEvent.isShiftPressed()) {
				if(view.getNextFocusLeftId() != -1) {
					findViewById(view.getNextFocusLeftId()).requestFocus();
				}
				else if(view.getNextFocusUpId() != -1) {
					findViewById(view.getNextFocusUpId()).requestFocus();
				}
			}
        	break;
		}
		return false;
	}
}